package com.css.zfzx.sjcj.modules.hddcwyTrench.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcTrench.repository.HddcTrenchRepository;
import com.css.zfzx.sjcj.modules.hddcTrench.repository.entity.HddcTrenchEntity;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.repository.entity.HddcWyFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyTrench.repository.HddcWyTrenchNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyTrench.repository.HddcWyTrenchRepository;
import com.css.zfzx.sjcj.modules.hddcwyTrench.repository.entity.HddcWyTrenchEntity;
import com.css.zfzx.sjcj.modules.hddcwyTrench.service.HddcWyTrenchService;
import com.css.zfzx.sjcj.modules.hddcwyTrench.viewobjects.HddcWyTrenchQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyTrench.viewobjects.HddcWyTrenchVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zyb
 * @date 2020-12-02
 */
@Service
@PropertySource(value = "classpath:platform-config.yml")
public class HddcWyTrenchServiceImpl implements HddcWyTrenchService {

	@Autowired
    private HddcWyTrenchRepository hddcWyTrenchRepository;
    @Autowired
    private HddcWyTrenchNativeRepository hddcWyTrenchNativeRepository;
    @Autowired
    private HddcTrenchRepository hddcTrenchRepository;

    @Value("${image.localDir}")
    private String localDir;
    @Value("${image.urlPre}")
    private String urlPre;

    @Override
    public JSONObject queryHddcWyTrenchs(HddcWyTrenchQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyTrenchEntity> hddcWyTrenchPage = this.hddcWyTrenchNativeRepository.queryHddcWyTrenchs(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyTrenchPage);
        return jsonObject;
    }


    @Override
    public HddcWyTrenchEntity getHddcWyTrench(String uuid) {
        HddcWyTrenchEntity hddcWyTrench = this.hddcWyTrenchRepository.findById(uuid).orElse(null);
         return hddcWyTrench;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyTrenchEntity saveHddcWyTrench(HddcWyTrenchEntity hddcWyTrench) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyTrench.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyTrench.getCreateUser())){
            hddcWyTrench.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyTrench.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyTrench.setIsValid("1");

        HddcTrenchEntity hddcTrenchEntity=new HddcTrenchEntity();
        BeanUtils.copyProperties(hddcWyTrench,hddcTrenchEntity);
        hddcTrenchEntity.setExtends4(hddcWyTrench.getTown());
        hddcTrenchEntity.setExtends5(String.valueOf(hddcWyTrench.getLon()));
        hddcTrenchEntity.setExtends6(String.valueOf(hddcWyTrench.getLat()));
        this.hddcTrenchRepository.save(hddcTrenchEntity);

        this.hddcWyTrenchRepository.save(hddcWyTrench);
        return hddcWyTrench;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyTrenchEntity updateHddcWyTrench(HddcWyTrenchEntity hddcWyTrench) {
        HddcWyTrenchEntity entity = hddcWyTrenchRepository.findById(hddcWyTrench.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyTrench);
        hddcWyTrench.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyTrench.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyTrenchRepository.save(hddcWyTrench);
        return hddcWyTrench;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyTrenchs(List<String> ids) {
        List<HddcWyTrenchEntity> hddcWyTrenchList = this.hddcWyTrenchRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWyTrenchList) && hddcWyTrenchList.size() > 0) {
            for(HddcWyTrenchEntity hddcWyTrench : hddcWyTrenchList) {
                this.hddcWyTrenchRepository.delete(hddcWyTrench);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyTrench(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyTrenchNativeRepository.queryHddcWyTrench(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyTrenchEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyTrenchEntity> list = hddcWyTrenchRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }



    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyTrenchEntity> hddcWyTrenchEntity = hddcWyTrenchNativeRepository.exportTrench(queryParams);
        List<HddcWyTrenchVO> list=new ArrayList<>();
        for (HddcWyTrenchEntity entity:hddcWyTrenchEntity) {
            HddcWyTrenchVO hddcWyTrenchVO=new HddcWyTrenchVO();
            BeanUtils.copyProperties(entity,hddcWyTrenchVO);
            list.add(hddcWyTrenchVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"探槽-点","探槽-点", HddcWyTrenchVO.class,"探槽-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWyTrenchVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyTrenchVO.class, params);
            List<HddcWyTrenchVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWyTrenchVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWyTrenchVO hddcWyTrenchVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + hddcWyTrenchVO.getRowNum() + "行" + hddcWyTrenchVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcWyTrenchVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWyTrenchEntity hddcWyTrenchEntity = new HddcWyTrenchEntity();
            HddcWyTrenchVO hddcWyTrenchVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcWyTrenchVO, hddcWyTrenchEntity);
            saveHddcWyTrench(hddcWyTrenchEntity);
        }
    }


    @Override
    public List<HddcWyTrenchEntity> findAllByCreateUserAndIsValid(String userId,String isValid) {
        List<HddcWyTrenchEntity> list = hddcWyTrenchRepository.findAllByCreateUserAndIsValid(userId,isValid);
        return list;
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyTrenchEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyTrenchRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyTrenchEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyTrenchRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyTrenchEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyTrenchRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyTrenchEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyTrenchRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }














}
